package com.konglz.consumer.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import java.io.IOException;

/**
 * @Description
 * @Author konglz
 * @Data 2023/5/13 13:21
 */
public class TopicMessageListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topicQueue1"),
            exchange = @Exchange(name = "konglz.topic", type = ExchangeTypes.TOPIC),
            key = {"user.#"}
    ))
    public void listenTopicQueue1(String message) {
        System.out.println("topicQueue1消费者接收到的消息：" + message);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topicQueue2"),
            exchange = @Exchange(name = "konglz.topic", type = ExchangeTypes.TOPIC),
            key = {"#.log"}
    ))
    public void listenTopicQueue2(String message) {
        System.out.println("topicQueue2消费者接收到的消息：" + message);
    }

    //============================================================================================================

    @RabbitListener(queues = "zhangShan")
    public void listenTopicQueueZhangShan(String message) {
        System.out.println("zhangShan消费者接收到的消息：" + message);
    }

    /**
    * @Description: 开启制动应答机制，手动应答，两次重试不成功之后，加入死信队列
    * @return: void
    * @Author: konglz
    * @Date: 2023/5/13
    */
    @RabbitListener(queues = "lisi")
    public void listenTopicQueueLisi(String mes, Message message, Channel channel) throws IOException {

        try {
            //模拟消费失败，造成请求重试
            //int i = 1 / 0;
            System.out.println("lisi消费者接收到的消息：" + mes);
            //false代表单个确认，true代表批量确认，第一个参数是消息标识符
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            e.printStackTrace();
            if (redelivered) {
                //进入if是第二次重试，设置不重试了
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                //进入else代表是第一次重试
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
